using Framework;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Events;

[System.Serializable]
struct MachineEvent
{
    public string name;
    public UnityEvent unityEvent;
}

public class StateEventMachine : MonoBehaviour
{
    [SerializeField]
    MachineEvent[] events = new MachineEvent[0];
    Dictionary<string, UnityEvent> event2Action;

    private void Awake()
    {
        event2Action = new Dictionary<string, UnityEvent>(events.Length * 2);
        foreach(var e in events)
        {
            if (string.IsNullOrEmpty(e.name))
            {
                SLogger.E("Event Name Can Not Be Empty");
                continue;
            }

            if(event2Action.ContainsKey(e.name))
            {
                SLogger.E($"Event [{e.name}] Repeated");
                continue;
            }
            event2Action.Add(e.name, e.unityEvent);
        }
    }
    public void Set(string eventName)
    {
        if(!string.IsNullOrEmpty(eventName) && event2Action.TryGetValue(eventName,out var actions) && null != actions)
        {
            actions.Invoke();
        }
    }

    public void TrySetEventByIndex(int index)
    {
        event2Action = new Dictionary<string, UnityEvent>(events.Length * 2);
        foreach (var e in events)
        {
            if (string.IsNullOrEmpty(e.name))
            {
                SLogger.E("Event Name Can Not Be Empty");
                continue;
            }

            if (event2Action.ContainsKey(e.name))
            {
                SLogger.E($"Event [{e.name}] Repeated");
                continue;
            }
            event2Action.Add(e.name, e.unityEvent);
        }

        if (events.Length > 0 && index >= 0 && index < events.Length)
        {
            Set(events[index].name);
        }
    }
}
